<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Cache;
use think\Config;
use app\admin\model\AdminLog;
use app\common\model\AuthRule;
class BaseController extends Controller
{
  protected $user_id;
  protected $user;

  public function __construct(\think\Request $request = null) {
    parent::__construct($request);

    // 读取网站设置
    settings();

    $site_root = Config::get("site_root");
    $this->assign("site_root", $site_root);
    
    // 当前页面记录
    $this->request = Request::instance();

    $manager = login_manager();
    if (empty($manager)) {
      if($this->request->isGet()){
        $this->redirect('login/login');
      }else{
        $this->error('请登陆', 'login/login', '', 0);
      }
    }

    $this->user_id = session('user_id');
    $this->user = session('user_name');

    
    $ctrl_name = $this->request->controller();
    $act_name = $this->request->action();
    $menu_name = $ctrl_name."/".$act_name;

    //权限检查
    // if (!$this->_checkAuthor($this->user_id)) {
    //   $this->error('你无权限操作');
    // }
   
    $MenuModel = new AuthRule();
    //树状态结构菜单
    $key_name = Config::get("cache_keys.menu_tree_name");
    $menu_tree = Cache::get($key_name);
    if(empty($menu_tree)){
      $menu_tree = $MenuModel->findWithDescendants("manager", 0);
      // 缓存过期时间在config.php文件里设置
      Cache::set($key_name, $menu_tree);
    }
    $this->assign("menu_tree", $menu_tree);
    
    //数组结构菜单--用来判断树状菜单里哪些menu选中。显示当前页面标题、面包屑
    $key_name = Config::get("cache_keys.menu_expland_name");
    $expland_menu = Cache::get($key_name);
    if(empty($expland_menu)){
      $rules = $MenuModel->explandWithDescendants("manager", [], 0);
      $expland_menu = [];
      foreach ($rules as $key => $item) {
        $key = $item["name"];
        $expland_menu[$key] = $item;
      }
      // 缓存过期时间在config.php文件里设置
      Cache::set($key_name, $expland_menu);
    }
    if(isset($expland_menu[$menu_name])){
      $current_page = $expland_menu[$menu_name];
    }else{
      $current_page = NULL;
    }
    $this->assign("current_page", $current_page);
    $this->current_page = $current_page;

    // 当前页面对应的面包屑
    if(empty($current_page)){
      $current_ancestor_ids = [];
      $breadcrumb = [];
    }else{
      $current_ancestor_ids = $current_page["with_ancestor_ids"];
      $sort_ids = implode(",", $current_ancestor_ids);
      $breadcrumb = $MenuModel->where("id", "IN", $sort_ids)->order("FIELD(id, {$sort_ids})")->select();
    }
    $this->assign("current_ancestor_ids", $current_ancestor_ids);
    $this->assign("breadcrumb", $breadcrumb);
    $this->current_ancestor_ids = $current_ancestor_ids;

    //记录日志
    $AdminLog = new AdminLog;
    $AdminLog->add($manager);
  }
}
